package code.easy.refresh

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.MutatorMutex
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue


class RefreshState {
    private val _indicatorOffset = Animatable(0f)
    private val mutatorMutex = MutatorMutex()

    var isRefreshing: Boolean = false
        set(value) {
            state = if (value) State.Refresh else State.Finish
            field = value
        }
        get() = state == State.Null

    internal var state by mutableStateOf(State.Null)

    val indicatorOffset: Float get() = _indicatorOffset.value

    internal suspend fun animateOffsetTo(offset: Float, duration:Long) {
        _indicatorOffset.animateTo(offset, TweenSpec(duration.toInt()))
    }

    internal suspend fun dispatchScrollDelta(delta: Float) {
        mutatorMutex.mutate(MutatePriority.UserInput) {
            _indicatorOffset.snapTo(_indicatorOffset.value + delta)
        }
    }

    enum class State {
        /** 空闲*/
        Null,
        /** 下拉中*/
        Pull,
        /** 刷新中*/
        Refresh,
        /** 刷新完毕收起中*/
        Finish,
        /** 下拉后没有触发刷新直接收起中*/
        Close,
    }
}
